package com.ctshk.rpc.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.req.MainData;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.system.dto.MainDataCollectionTypeDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.dto.mian.data.MainDataComprehensiveServiceDetailDTO;
import com.ctshk.rpc.system.dto.mian.data.MainDataComprehensiveServiceListDTO;
import com.ctshk.rpc.system.entity.MainDataCollectionType;
import com.ctshk.rpc.system.entity.MainDataComprehensiveService;
import com.ctshk.rpc.system.mapper.MainDataComprehensiveServiceMapper;
import com.ctshk.rpc.system.req.main.data.MainDataComprehensiveServiceAddReq;
import com.ctshk.rpc.system.req.main.data.MainDataComprehensiveServiceIdReq;
import com.ctshk.rpc.system.req.main.data.MainDataComprehensiveServiceListReq;
import com.ctshk.rpc.system.service.IMainDataComprehensiveServiceService;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 主数据-综费服务类型 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-06-03
 */
@DubboService
public class MainDataComprehensiveServiceServiceImpl extends ServiceImpl<MainDataComprehensiveServiceMapper, MainDataComprehensiveService> implements IMainDataComprehensiveServiceService {

    @Autowired
    private MainDataComprehensiveServiceMapper mainDataComprehensiveServiceMapper;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 列表
     *
     * @param req
     * @return
     */
    @Override
    public Result<PageResponse<MainDataComprehensiveServiceListDTO>> list(MainDataComprehensiveServiceListReq req) {
        IPage<MainDataComprehensiveService> pageParam = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<MainDataComprehensiveService> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(req.getComprehensiveFeeId() != null,"comprehensive_fee_id",req.getComprehensiveFeeId());
        queryWrapper.eq("is_deleted",0);
        queryWrapper.eq(req.getStatus() != null,"status",req.getStatus());
        queryWrapper.like(StringUtils.isNotBlank(req.getComprehensiveServiceName()),"comprehensive_service_name",req.getComprehensiveServiceName());
        IPage<MainDataComprehensiveService> iPage = mainDataComprehensiveServiceMapper.selectPage(pageParam, queryWrapper);
        List<MainDataComprehensiveService> records = iPage.getRecords();
        List<MainDataComprehensiveServiceListDTO> dtoList = EntityUtil.copyList(records, MainDataComprehensiveServiceListDTO.class);
        dtoList.forEach(dto -> {
            if (dto.getModifiedId() != null){
                UserDTO userDTO = sysUserService.queryCacheUser(dto.getModifiedId());
                if (userDTO != null){
                    dto.setModifiedName(new StringBuffer(userDTO.getFullName()+"/"+userDTO.getDept()).toString());
                }
            }
        });
        PageResponse<MainDataComprehensiveServiceListDTO> pageResponse = new PageResponse<>(dtoList,
                iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                iPage.getTotal(), iPage.getCurrent(),
                iPage.getSize());
        return Result.success(pageResponse);
    }


    /**
     * 查询列表
     *
     * @param name
     * @return
     */
    @Override
    public Result<List<MainData>> query(String name) {
        List<MainData> list = new ArrayList<>();
        QueryWrapper<MainDataComprehensiveService> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name) && !"1".equals(name),"comprehensive_service_name",name);
        queryWrapper.eq("status",0);
        queryWrapper.eq("is_deleted",0);
        List<MainDataComprehensiveService> selectList = mainDataComprehensiveServiceMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(selectList)){
            for (MainDataComprehensiveService service : selectList) {
                MainData dto = new MainData();
                dto.setValue(service.getId());
                dto.setLabel(service.getComprehensiveServiceName());
                list.add(dto);
            }
        }
        return Result.success(list);
    }


    /**
     * 详情
     *
     * @param req
     * @return
     */
    @Override
    public Result<MainDataComprehensiveServiceDetailDTO> detail(MainDataComprehensiveServiceIdReq req) {
        MainDataComprehensiveService service = getById(req.getId());
        if (service == null || Objects.equals(service.getIsDeleted(),1)){
            throw new BusinessException(SystemError.SYS_411);
        }
        MainDataComprehensiveServiceDetailDTO dto = EntityUtil.copy(service,MainDataComprehensiveServiceDetailDTO.class);
        return Result.success(dto);
    }

    /**
     * 新增/编辑
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(MainDataComprehensiveServiceAddReq req) {
        MainDataComprehensiveService service = null;
        int type = 1;
        if (req.getId() != null){
            service = getById(req.getId());
            if (service == null || Objects.equals(service.getIsDeleted(),1)){
                throw new BusinessException(SystemError.SYS_411);
            }
            type = 2;
            service.setModifiedId(req.getUserId());
        }else{
            service = new MainDataComprehensiveService();
            service.setId(SnowflakeIdWorker.nextId());
            service.setCreateId(req.getUserId());
            service.setGmtCreate(LocalDateTime.now());
            service.setIsDeleted(0);
        }
        service = EntityUtil.copy(req,MainDataComprehensiveService.class);
        boolean bl = false;
        if (type == 1){
            bl = save(service);
        }else if (type == 2){
            bl = updateById(service);
        }
        if (!bl){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(service.getId());
    }

    /**
     * 删除
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result del(MainDataComprehensiveServiceIdReq req) {
        MainDataComprehensiveService service = getById(req.getId());
        if (service == null){
            throw new BusinessException(SystemError.SYS_411);
        }
        if (Objects.equals(service.getIsDeleted(),1)){
            return Result.success(service.getId());
        }
        service.setIsDeleted(1);
        service.setModifiedId(req.getUserId());
        boolean bl = updateById(service);
        if (!bl){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(service.getId());
    }

    /**
     * 修改状态
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result changeStatus(MainDataComprehensiveServiceIdReq req) {
        MainDataComprehensiveService service = getById(req.getId());
        if (service == null || Objects.equals(service.getIsDeleted(),1)){
            throw new BusinessException(SystemError.SYS_411);
        }
        int status = service.getStatus() == 0?1:0;
        service.setStatus(status);
        service.setModifiedId(req.getUserId());
        boolean bl = updateById(service);
        if (!bl){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(service.getId());
    }

}
